<template>
  <view class="container_cer">
    <view class="toOther" v-if="type">
      未找到身份证照片
      <view
        class="toOtherBtn"
        @click="$onTo('pages/certificatesNoPhoto/certificatesNoPhoto')"
        >稍后再补拍</view
      >
    </view>
    <view class="content">
      <view class="item" @click="update('1')">
        <view class="item-l">
          <view class="item-l-title">头像面</view>
          <view class="item-l-text">上传您的身份证头像面</view>
        </view>
        <view class="update update-fir">
          <view class="update-border">
            <image
              :src="frontUrl"
              class="update-img"
              mode="scaleToFill"
              v-if="frontUrl"
            ></image>
            <image
              v-else
              class="update-img"
              src="https://zuwuzu.oss-cn-shanghai.aliyuncs.com/certificate/man-front.png"
              mode="scaleToFill"
            ></image>
          </view>
        </view>
      </view>
      <view class="item" @click="update('2')">
        <view class="item-l">
          <view class="item-l-title">国徽面</view>
          <view class="item-l-text">上传您的身份证国徽面</view>
        </view>
        <view class="update update-sed">
          <view class="update-border">
            <image
              :src="backUrl"
              class="update-img"
              mode="scaleToFill"
              v-if="backUrl"
            ></image>
            <image
              v-else
              class="update-img"
              src="https://zuwuzu.oss-cn-shanghai.aliyuncs.com/certificate/man-back.png"
              mode="scaleToFill"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <view class="header-view"></view>

    <form report-submit="true" @submit="formSubmit">
      <view class="realName-page">
        <view class="contents">
          <view class="contents-item">
            <view class="contents-item-view">
              <view>姓名</view>
              <input
                class="contents-item-input"
                placeholder="上传身份证后自动识别"
                disabled
                name="userName"
                :value="identityData.userName"
              />
            </view>
          </view>

          <view class="contents-item">
            <view class="contents-item-view">
              <view>身份证号</view>
              <input
                class="contents-item-input"
                placeholder="上传身份证后自动识别"
                name="idcard"
                disabled
                :value="identityData.idCardNo"
              />
            </view>
          </view>
          <view class="contents-item">
            <view class="contents-item-view">
              <view
                :style="{
                  display: 'flex',
                  alignItems: 'center',
                }"
              >
                身份证到期日
                <image
                  src="https://zuwuzu.oss-cn-shanghai.aliyuncs.com/certificate/icon-wenhao.png"
                  :style="{
                    display: 'block',
                    width: '14px',
                    height: '14px',
                    marginLeft: '4px',
                  }"
                  @click="isVisible"
                ></image>
              </view>
              <input
                class="contents-item-inputs"
                placeholder="上传身份证后自动识别"
                name="limitDate"
                disabled
                :value="identityData.limitDate"
              />
            </view>
          </view>
          <view class="header-view"></view>

          <view class="contents-item">
            <view class="contents-item-view">
              <input
                class="contents-item-input"
                placeholder="请输入手机号"
                type="number"
                name="mobile"
                style="text-align: left"
                @input="handleMobile"
                v-model="mobile"
              />
            </view>
          </view>
          <view class="contents-item" :style="{ borderBottom: 0 }">
            <view class="contents-item-view">
              <view class="contents-item-inner" :style="{ flexGrow: 1 }">
                <input
                  class="contents-item-inner-input"
                  placeholder="请输入短信验证码"
                  type="number"
                  name="smsCode"
                />
                <view v-if="count" class="contents-item-inner-small">
                  {{ count }}S
                </view>
                <view class="contents-item-inner-small" v-else @click="getCode">
                  获取验证码
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="header-view"></view>
        <view class="header">温馨提示：</view>
        <view class="header"
          >请上传本人身份证照片，非本人信息无法通过审核。</view
        >
        <view class="header">确保证件边框完整，文字清晰可见；</view>
        <view class="header">可现场拍摄或从手机相册获取。</view>
        <view class="bottom-view">
          <!-- class={checked ? "bottom-button" : "bottom-button disabled"} -->
          <button form-type="submit" class="bottom-button">提交</button>
        </view>
      </view>
    </form>
    <cmd-curtain :visible="visible" mode="top-right">
      <image
        mode="scaleToFill"
        src="https://booleandata-zuwuzu.oss-cn-beijing.aliyuncs.com/ip12/shenfen1.png"
        style="width: 100%; height: 250px"
      ></image>
    </cmd-curtain>
  </view>
</template>

<script>
import { errHandler, saveUserId, loginHandler } from "../../utils/index"
import cmdCurtain from "@/components/cmd-curtain/cmd-curtain.vue"
import { shareConfigObj } from "../../utils/constant"

export default {
  data() {
    return {
      frontUrl: null,
      backUrl: null,
      identityData: {
        idCardNo: "",
        limitDate: "",
        userName: "",
      },
      count: 0,
      mobile: "",
      visible: false,
      smsApiRes: {}, // 获取短信接口所返回的数据
      type:true
    }
  },

  onLoad(e) {
    if(e.type === "my")this.type = false
  },

  onShareAppMessage() { // 禁止分享当前页面，避免提交后点击回退按钮没有反应
    return shareConfigObj
  },

  components: { cmdCurtain },
  methods: {
    formSubmit: function (e) {
      const { userName, idcard, mobile, smsCode, limitDate } = e.detail.value
      if (!userName) {
        uni.showToast({ title: "身份信息有误，请检查后重新上传" })
        return
      }
      if (!limitDate) {
        uni.showToast({ title: "身份信息有误，请检查后重新上传" })
        return
      }
      if (!idcard || idcard.length !== 18) {
        uni.showToast({ title: "身份信息有误，请检查后重新上传" })
        return
      }
      if (!mobile || mobile.length !== 11) {
        uni.showToast({ title: "请输入正确的手机号" })
        return
      }
      if (!smsCode) {
        uni.showToast({ title: "请输入短信验证码" })
        return
      }
      const postObj = {
        uid: this.$getUid(),
        userName,
        idCard: idcard,
        telephone: mobile,
        codeKey: this.smsApiRes?.codeKey,
        smsCode,
        codeTime: this.smsApiRes?.codeTime,
        idCardFrontUrl: this.frontUrl,
        idCardBackUrl: this.backUrl,
        limitDate,
      }
      const { postData, pass } = this.$postDataGuard(postObj)
      if (!pass) return
      if (this.submiting) return
      this.submiting = true
      this.$request("hzsx/userCertification/userCertificationAuth", postData, "POST", false, true).then(res => {
        const newUid = res.data // 用户新的uid
        if (newUid) { // 更新uid，多平台渠道的话可以进行用户整合
          saveUserId(newUid) // 注意这里只更新了localStorage中单独的uid数据，并没有更新localStorage中userDetail里面的uid，所以在取uid的时候最好使用单独的uid字段
        }
        loginHandler(true, {}, null, true, false) // 调用接口重新保存我的信息，防止某些功能取身份证姓名一直获取不到，需要重新登录才行，注：该方法具有覆盖uid的副作用
        this.$eventEmitter.emit("refreshShiminRenZhengStatus") // 通知我的页面重新判断一下实名认证状态
        this.$eventEmitter.emit("refreshMyPageConfigData") // 通知我的页面重新拉取一下订单，以防止在其它平台下了单，实名认证回到我的页面订单气泡还是没变
        uni.navigateBack()
      }).finally(() => {
        this.submiting = false
      })
    },
    handleMobile(e) {
      this.mobile = e.detail.value
    },
    //打开到期身份证示意图
    isVisible() {
      this.visible = !this.visible
    },
    //发送验证码
    getCode() {
      //校验手机号
      if (!/^1(\d){10}$/.test(this.mobile + "")) {
        uni.showToast({ title: "请正确输入手机号" })
        return
      }
      this.$request(
        "hzsx/userCertification/sendSmsCode",
        { mobile: this.mobile },
        "get",
        true
      ).then((res) => {
        this.smsApiRes = res.data || {} // 提交身份证信息的时候需要用到验证码数据
        let count = 59
        this.count = count
        this.interval = setInterval(() => {
          count -= 1
          this.count = count
          if (count === 0) {
            clearInterval(this.interval)
          }
        }, 1000)
        uni.showToast({ title: "验证码已发送，5分钟内有效" })
      })
    },
    /**
     * 上传身份证号
     * @param val:1表示正面，2表示反面
     */
    update(val) {
      if (val === "1") {
        my.chooseImage({
          count: 1, //只能上传选择一张
          sizeType: ["compressed"],
          success: (res) => {
            // const { tempFilePaths } = res
            const tempFilePaths = res.apFilePaths
            if (
              Object.prototype.toString.call(tempFilePaths) !== "[object Array]"
            ) {
              errHandler("请重新选择图片", true)
              return
            }
            const fileUploadPromises = tempFilePaths.map((tempFileUrl) =>
              this.$fileUploadHandler(tempFileUrl)
            )
            Promise.all(fileUploadPromises).then((imgUrls) => {
              // 图片上传成功
              this.frontUrl = imgUrls[0]
              if (this.frontUrl && this.backUrl) {
                //调用OCR识别逻辑
                this.$request(
                  "hzsx/userCertification/certificationOcr",
                  {
                    frontUrl: this.frontUrl,
                    backUrl: this.backUrl,
                    uid: this.$getUid(),
                  },
                  "post"
                )
                  .then((res) => {
                    this.identityData = res.data
                  })
                  .catch((err) => {
                    this.frontUrl = null
                    this.backUrl = null
                  })
              }
            })
          },
        })
      }
      if (val === "2") {
        my.chooseImage({
          count: 1,
          sizeType: ["compressed"],
          success: (res) => {
            // const { tempFilePaths } = res
            const tempFilePaths = res.apFilePaths
            if (
              Object.prototype.toString.call(tempFilePaths) !== "[object Array]"
            ) {
              errHandler("请重新选择图片", true)
              return
            }
            const fileUploadPromises = tempFilePaths.map((tempFileUrl) =>
              this.$fileUploadHandler(tempFileUrl)
            )
            Promise.all(fileUploadPromises).then((imgUrls) => {
              // 图片上传成功
              this.backUrl = imgUrls[0]
              if (this.frontUrl && this.backUrl) {
                //调用OCR识别逻辑
                this.$request(
                  "hzsx/userCertification/certificationOcr",
                  {
                    frontUrl: this.frontUrl,
                    backUrl: this.backUrl,
                    uid: this.$getUid(),
                  },
                  "post"
                )
                  .then((res) => {
                    this.identityData = res.data
                  })
                  .catch((err) => {
                    this.frontUrl = null
                    this.backUrl = null
                  })
              }
            })
          },
        })
      }
    },
  },
}
</script>

<style lang="scss">
.container_cer {
  @include wh(100%, 100vh);
  background: #f5f5f5;
  font-family: PingFangSC-Regular;
  padding-top: 1rpx;
  .header-view {
    height: 20rpx;
    background: #f3f4f9;
  }
  .toOther {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 30rpx;
    width: 750rpx;
    height: 100rpx;
    @include global-background-color();
    font-size: 28rpx;
    color: #333333;
    font-weight: 400;
    margin-bottom: 20rpx;
    .toOtherBtn {
      width: 150rpx;
      height: 50rpx;
      border-radius: 49rpx;
      background: #1f2129;
      box-shadow: 0px 2px 4px 0px rgba(252, 73, 93, 0.5);
      font-size: 24rpx;
      @include global-color();
      font-weight: 400;
      line-height: 50rpx;
      text-align: center;
    }
  }
  .content {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    background: #fff;
    box-sizing: border-box;
    padding: 20rpx 0;
    border-radius: 20rpx;
    .item {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      position: relative;
      background: #f7f8fa;
      border-radius: 10rpx;
      width: 691rpx;
      height: 307rpx;
      margin: 10rpx auto;
      box-sizing: border-box;
      padding: 30rpx 34rpx;
      .item-l {
        .item-l-title {
          font-family: PingFangSC-Medium;
          font-size: 38rpx;
          color: #333333;
          font-weight: bold;
          margin-bottom: 10rpx;
        }
        .item-l-text {
          font-family: PingFangSC-Regular;
          font-size: 24rpx;
          color: #586e98;
          font-weight: 400;
        }
      }

      .update {
        @include wh(370rpx, 243rpx);
        background: #e0f0ff;
        display: flex;
        align-items: center;
        justify-content: center;
        .update-border {
          width: 336rpx;
          height: 218rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: url("https://zuwuzu.oss-cn-shanghai.aliyuncs.com/certificate/man-bg.png")
            no-repeat;
          background-size: 100% 100%;
        }
      }
      .update-img {
        @include wh(322rpx, 204rpx);
      }
    }
  }
  .realName-page {
    @include wh(100%, 100%);

    .contents {
      .brb {
        border-bottom: 1rpx rgba(240, 240, 240, 1) solid;
      }
      .mt20 {
        margin: 20rpx 0 0 0;
      }
      .imgss {
        width: 22rpx;
        height: 22rpx;
      }
      .contents-item-view {
        height: 100rpx;
        width: 100%;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-family: PingFangSC-Regular;
        color: #333333;
        font-size: 30rpx;
        padding: 20rpx 0;
      }
      &-item {
        height: 100rpx;
        .phone-btn {
          color: #fc766b;
          font-family: PingFangSC-Regular;
          border: none;
          font-size: 30rpx;
          height: 45rpx;
          width: 200rpx;
          line-height: 45rpx;
        }
        .contents-item-input,
        .contents-item-inputs {
          text-align: right;
          padding-left: 0;
        }
        .contents-item-inner-input {
          padding-left: 0;
        }
        box-sizing: border-box;
        background-color: #fff;

        font-family: PingFangSC-Regular;
        color: #333333;
        font-size: 30rpx;
        padding: 0 30rpx;

        &-input {
          text-align: left;
          font-size: 30rpx;
          width: calc(100% - 200rpx);
        }
        &-inputs {
          text-align: left;
          font-size: 30rpx;
          width: calc(100% - 255rpx);
        }
        &-inner {
          display: flex;
          justify-content: space-between;
          align-items: center;
          &-input {
            text-align: left;
            font-size: 30rpx;
            width: 280rpx;
          }
          &-image {
            height: 64rpx;
            width: 160rpx;
          }
          &-small {
            color: #fc766b;
            font-size: 28rpx;
          }
        }
      }
    }
    .forget {
      text-align: right;
      padding: 30rpx;
      font-family: PingFangSC-Regular;
      color: #666666;
      font-size: 26rpx;
      &-text {
        color: #fc766b;
      }
    }
    .xieyi {
      margin: 60rpx 30rpx 20rpx 30rpx;
      font-size: 24rpx;
      color: #999;
      .libs {
        display: flex;

        margin: 0 auto;
        justify-content: center;
        .img {
          @include wh(25rpx, 25rpx);
          margin: 2rpx 5rpx 0 0;
        }
      }
      .checkbox-text {
        .text {
          color: #c43737;
        }
      }
    }
    .bottom-view {
      background-color: #f3f4f9;
      box-sizing: border-box;
      padding: 80rpx 0 30rpx 0;
    }
    .bottom-button {
      width: 650rpx;
      height: 98rpx;
      @include global-background-color();
      border-radius: 49rpx;
      font-family: PingFangSC-Regular;
      font-size: 34rpx;
      color: #333333;
      text-align: center;
      letter-spacing: 0;
      line-height: 98rpx;
      font-weight: 700;
      margin: 0 auto;

    }
    .disabled {
      background-color: #c43737;
      opacity: 0.64;
    }
    .bottom-view {
      font-size: 28rpx;
      color: #999;
      text-align: center;
      &-text {
        color: #00a0ff;
      }
    }
    .header {
      background: #f3f4f9;
      font-family: PingFangSC-Regular;
      font-size: 24rpx;
      color: #999999;
      letter-spacing: 0;
      font-weight: 400;
      padding: 4rpx 0 4rpx 30rpx;
    }
  }
}
</style>
